package com.jizzotool.server;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.jizzotool.client.LoginService;
import com.jizzotool.client.User;
import com.jizzotool.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {

	public User login(String login, String password) throws IllegalArgumentException {
		User user = getUserAlreadyFromSession();
		if (user == null) {
			if (!FieldVerifier.isValidName(login) || !FieldVerifier.isValidName(password)) {
				throw new IllegalArgumentException();
			}
	
			user = new User(login, password);
			storeUserInSession(user);
		}
		return user;
	}

	private User getUserAlreadyFromSession() { 
		User user = null;
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		Object userObj = session.getAttribute("user");
		if (userObj != null && userObj instanceof User) {
			user = (User) userObj;
		}
		return user;
	}
	
	private void storeUserInSession(User user) {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		session.setAttribute("user", user);
	}
	
	public User loginFromSession() {
		User user = getUserAlreadyFromSession();
		return user;
	}
	
	public void logout() {
		deleteUserFromSession(); 
	}
	 
	private void deleteUserFromSession() {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		session.removeAttribute("user"); 
	}
}
